package young.service.impl;

import com.sun.source.tree.IfTree;
import young.dao.UserDAO;
import young.dao.impl.UserDAOImpl;
import young.pojo.UserDO;
import young.service.UserService;

/**
 * 业务处理
 */
public class UserServiceImpl implements UserService {
    private UserDAO userDAO = new UserDAOImpl();
    private Integer num=3;

    /**
     * @param id  账户
     * @param pwd 密码
     * @return
     */
    @Override
    public UserDO getByUsernameAndPwd(String id, String pwd) {
        return userDAO.getByUsernameAndPwd(id, pwd);
    }

    /**
     * 存款业务
     *
     * @param id    账户
     * @param money 存款金额
     */
    @Override
    public void saveMoney(String id, int money) {
        UserDO user = userDAO.getById(id);
        user.setMoney(user.getMoney() + money);
        userDAO.update(user, user);
    }

    /**
     * @param id    账户
     * @param money 取款金额
     */
    @Override
    public void getMoney(String id, int money) throws Exception {
        UserDO user = userDAO.getById(id);
        if (user.getMoney() >= money) {
            user.setMoney(user.getMoney() - money);
            userDAO.update(user, user);
        } else {
            throw new Exception("账户余额不足");
        }

    }

    /**
     * 转账业务
     *
     * @param loginId 当前账户
     * @param otherId 转入账户
     * @param money   转入金额
     * @throws Exception
     */
    @Override
    public void transferMoney(String loginId, String otherId, int money) throws Exception {
        UserDO login = userDAO.getById(loginId);
        UserDO other = userDAO.getById(otherId);


        if (login.getId().equals(otherId)) {
            throw new Exception("非法账户");
        }
        if (other.getId() == null) {
            throw new Exception("账户有误，请确认");

        }
        if (login.getMoney() >= money) {
            login.setMoney(login.getMoney() - money);
            other.setMoney(other.getMoney() + money);
            userDAO.update(login, other);
        } else {
            throw new Exception("账户余额不足");
        }

    }

    @Override
    public void revise(String id,String pwd, String newPwd, String newPwdTow) throws Exception {

        UserDO user = userDAO.getById(id);
        if (user.getPassword().equals(pwd)) {

            if (newPwd.equals(newPwdTow)) {
                user.setPassword(newPwdTow);
                userDAO.update(user, user);

            } else {
                throw new Exception("新密码输入不一致");

            }
        } else {
            throw new Exception("密码错误");

        }

    }


}
